import { CloseOutlined } from '@ant-design/icons';
import { Button, Descriptions, Drawer, Form, Input, Space, Spin } from 'antd';

import hooks from '../../hooks';
import AuthForm from './AuthForm';
import { MobileRegExp } from '@szzj/utils';

const layout = {
  labelCol: { span: 4 },
  wrapperCol: { span: 20 },
};

export default () => {
  const {
    tableHooks,
    editHooks: { editForm, modal, onClose, onSubmit, submitLoading, onSearch },
  } = hooks.useContainer();
  const data = modal.data;
  return (
    <Drawer
      title={modal.isEdit ? '编辑用户' : '新增用户'}
      width={600}
      destroyOnClose
      open={modal.open}
      footer={
        <Space>
          <Button
            type="primary"
            onClick={async () => {
              await onSubmit().then((res) => {
                if (res.success) {
                  tableHooks.refresh();
                }
              });
            }}
            loading={submitLoading}
            disabled={!modal.data}
          >
            保存
          </Button>
          <Button onClick={onClose}>关闭</Button>
        </Space>
      }
      extra={<CloseOutlined onClick={onClose} />}
      closable={false}
      onClose={onClose}
    >
      {!modal.isEdit && (
        <div style={{ marginBottom: 20 }}>
          <Input.Search
            placeholder="请输入手机号查询"
            allowClear
            enterButton="查询"
            onSearch={(value) => onSearch(Number(value))}
          />
        </div>
      )}
      {modal.data && (
        <Form {...layout} form={editForm} labelAlign="left">
          <Descriptions title="用户信息" layout="horizontal" column={1}>
            <Descriptions.Item label="姓名">{data?.userName}</Descriptions.Item>
            <Descriptions.Item label="手机号码">
              {modal.isEdit ? (
                <Form.Item
                  wrapperCol={{ span: 24 }}
                  style={{ marginTop: -4, width: '100%' }}
                  name="mobile"
                  rules={[{ pattern: MobileRegExp, message: '请输入正确的手机号码' }]}
                  initialValue={data?.mobile}
                >
                  <Input />
                </Form.Item>
              ) : (
                data?.mobile
              )}
            </Descriptions.Item>
            <Descriptions.Item label="所属部门" contentStyle={{ whiteSpace: 'pre-wrap' }}>
              {data?.deptNamePathList?.join('\n') ?? '-'}
            </Descriptions.Item>
          </Descriptions>
          <Descriptions title="授权管理" layout="vertical" column={1} />
          <AuthForm />
        </Form>
      )}
      {modal.loading && (
        <div style={{ display: 'flex', justifyContent: 'center', padding: '100px 0' }}>
          <Spin />
        </div>
      )}
    </Drawer>
  );
};
